package com.huaxin.hxcloud.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Entity.EquHistoryDTO;
import com.huaxin.common.Entity.Equipment;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author lwjing
 * @date 2018/2/1
 * @Desc $desc$
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxCollectRunStataActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar            mToolbar;
    @BindView(R.id.rv_runstata)
    RecyclerView       rv_runstata;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    private String mEquipmentId;
    private View   emptyView;

    public List<Equipment> datas  = new ArrayList<>();
    public int             pageNo = 0;
    private RunStataAdapter mAdapter;
    private final int PAGE_SIZE = 20;

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constant.EQUIPMENTID)) {
            mEquipmentId = extras.getString(Constant.EQUIPMENTID);
        } else {
            finish();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_run_stata;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        mToolbar.setTitle("设备" + mEquipmentId);
        setSupportActionBar(mToolbar);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        rv_runstata.setLayoutManager(manager);
        initAdapter();
        initRefreshLayout();
        mSwipeRefreshLayout.setRefreshing(false);

        //空布局
        emptyView = LayoutInflater.from(this).inflate(R.layout.item_empty_nodata_center, (ViewGroup) rv_runstata.getParent(), false);

    }

    @Override
    protected void requestData() {
        // super.requestData();
        //app/findEquHistory
        apiFindEquHistory(LOADING, false);
    }

    private void initRefreshLayout() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //  refresh();
                mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
                pageNo=0;
                apiFindEquHistory(LOAD_SUCCESS, true);
            }
        });
    }

    private void initAdapter() {
        mAdapter = new RunStataAdapter(R.layout.emq_run_stata_item, datas);

        //加载更多
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                apiFindEquHistory(LOAD_SUCCESS, false);
            }
        });
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.setPreLoadNumber(3);
        rv_runstata.setAdapter(mAdapter);

        //item点击事件
        rv_runstata.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {

            }
        });
    }


    /**
     * 获取对应设备操作历史记录
     *
     * @param isRefresh 是否下拉刷新
     */
    private void apiFindEquHistory(int stata, final boolean isRefresh) {
        updateLoadStatus(stata);
        Call<EquHistoryDTO> call = HxTransmitRequestHelper.getRequestApi().getFindEquHistory(mEquipmentId, pageNo);
        autoClose(call);
        call.enqueue(new Callback<EquHistoryDTO>() {

            @Override
            public void onResponse(Call<EquHistoryDTO> call, Response<EquHistoryDTO> response) {
                EquHistoryDTO runStataDTO = response.body();
                if (response.isSuccessful() && runStataDTO != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    List<Equipment> equipments = runStataDTO.getData();
                    if (equipments != null && equipments.size() > 0) {
                        if (isRefresh) {
                            //下拉刷新
                            setData(isRefresh, equipments);
                            mAdapter.setEnableLoadMore(true);
                            if (mSwipeRefreshLayout !=null){
                                mSwipeRefreshLayout.setRefreshing(false);
                            }
                        } else {
                            //加载更多
                            setData(isRefresh, equipments);
                        }
                    } else {
                        if (pageNo == 0) {
                            //设置null布局
                            mAdapter.setEmptyView(emptyView);
                        }else{
                            mAdapter.loadMoreEnd(isRefresh);
                        }
                        if (isRefresh) {
                            mAdapter.setEnableLoadMore(true);
                            if (mSwipeRefreshLayout !=null){
                                mSwipeRefreshLayout.setRefreshing(false);
                            }
                        }
                    }

                } else {
                    if (pageNo == 0) {
                        updateLoadStatus(LOAD_ERROR);
                    }
                    if (isRefresh) {
                        mAdapter.setEnableLoadMore(true);
                        if (mSwipeRefreshLayout !=null){
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<EquHistoryDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
                if (isRefresh) {
                    mAdapter.setEnableLoadMore(true);
                    if (mSwipeRefreshLayout !=null){
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                } else {
                    mAdapter.loadMoreFail();
                }
            }
        });
    }

    private void setData(boolean isRefresh, List data) {
        pageNo++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }


    class RunStataAdapter extends BaseQuickAdapter<Equipment, BaseViewHolder> {


        public RunStataAdapter(int layoutResId, @Nullable List<Equipment> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, Equipment equipment) {
            TextView time = baseViewHolder.getView(R.id.tv_time);
            TextView stata = baseViewHolder.getView(R.id.tv_stata);
            time.setText(equipment.getTime());
            stata.setText(equipment.getSwichingValue());
        }
    }
}
